// Copyright (c) XiGuan 2023
// Author： xiguan
// Email: xiguan.teng@qq.com
// Create on 2023/11/15
// TODO:
//

#include "Epoller.h"

#include <assert.h>
#include <unistd.h>

Epoller::Epoller(int max_event)
    : epoll_fd_(epoll_create(512)), epoll_events_(max_event) {
  assert(epoll_fd_ >= 0 && epoll_events_.size() > 0);
}

Epoller::~Epoller() { close(epoll_fd_); }

bool Epoller::add_fd(int fd, uint32_t event) {
  if (fd < 0) {
    return false;
  }

  epoll_event ev = {0};
  ev.data.fd = fd;
  ev.events = event;

  return 0 == epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev);
}

bool Epoller::mod_fd(int fd, uint32_t event) {
  if (fd < 0) {
    return false;
  }

  epoll_event ev = {0};
  ev.data.fd = fd;
  ev.events = event;

  return 0 == epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &ev);
}

bool Epoller::del_fd(int fd) {
  if (fd < 0) {
    return false;
  }

  epoll_event ev = {0};

  return 0 == epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &ev);
}

int Epoller::wait(int timeout) {
  return epoll_wait(epoll_fd_, &(epoll_events_[0]),
                    static_cast<int>(epoll_events_.size()), timeout);
}

int Epoller::GetEventFd(size_t idx) const {
  assert(idx < epoll_events_.size() && idx >= 0);
  return epoll_events_[idx].data.fd;
}

uint32_t Epoller::GetEvent(size_t idx) const {
  assert(idx < epoll_events_.size() && idx >= 0);
  return epoll_events_[idx].events;
}
